/** @jsxImportSource @emotion/react */
import {  css } from "@emotion/react";
import React from 'react'
import {useDrag} from '@use-gesture/react'
import {animated, useSpring} from '@react-spring/web'
import {useControls} from 'leva'
import {UserDragConfig} from "@use-gesture/core/types";
import {
    useTheme,InputLine,
    Button,InputGroup,Input,
    TabPanel,CommitInput
} from "customize-easy-ui-component";

/**测试动画库拖拽等
 * */
interface NestedStackProps {
    //可支持搜索菜单项目的 文本。
    label?: string;
    //实际 没必要的参数
    nested?: boolean;
    children?: React.ReactNode;
    //后面安放的图标
    // contentAfter?: React.ReactNode;
    //前面安放的图标
    //  contentBefore?: React.ReactNode;
    //任意的组件， 简易按钮 图标
    icon?: React.ReactNode;
    //菜单按钮的样式 ：还是能独立配置为佳。
    divStyle?: React.CSSProperties;
    /**可以将这里没定义的参数 tight={true} 透明传递下去。
     * */
    [key: string]: any;     //任意参数传递模式！
}

const NestedStack = React.forwardRef<
    HTMLDivElement,
    NestedStackProps & React.HTMLProps<HTMLDivElement>
    >((props, ref) => {
    const ref3 = React.useRef<HTMLDivElement | null>(null);
    const [color, setColor] = React.useState('white')
    const toggleColor = () => setColor((c) => (c === 'white' ? '#ec625c' : 'white'))

    const [style, api] = useSpring(() => ({ scale: 1, x: 0, y: 0 }))
    const [styleOuter, apiOuter] = useSpring(() => ({scale: 1, x: 0, y: 0 }))
    const [coords, set] = React.useState({ x: 0, y: 0 })

    const { boundToParent, gesture, ...options } = useControls({
        enabled: true,
        gesture: { options: ['offset', 'movement'] },
        axis: { options: [undefined, 'x', 'y', 'lock'] },
        filterTaps: false,
        boundToParent: false,
        rubberband: false,
        triggerAllEvents: true
    })

    const pointerOptions = useControls('pointer', { touch: false, capture: true, lock: false })
//第一层bindOuter不可以当做第三层来用的！拉动第三层会同时拉动第二层。
//     const bindOuter_First = useDrag((state) =>{
//             const { offset: [x, y] }=state;
//             console.log("框架第三层 graphql入口data=" ,state);
//             apiOuter.start({ x, y })
//         }
//     )

    const config3= {
        filterTaps: true,
        triggerAllEvents: true,
        pointer: { touch: false, capture: true, lock: false },
         // ...(boundToParent && { bounds: ref })  as any
    } as UserDragConfig;

    const bindOuter = useDrag(
        (state) => {
            const { event, active, intentional, tap,
                           canceled, ...other }=state;
            console.log("框架第三层 graphql入口data=" ,state);
            event.stopPropagation()
            if (intentional) {
                // @ts-ignore
                let [x, y] = other[gesture];     //['offset', 'movement']
                // set({ x, y })

                if (pointerOptions.lock) {
                    const dx = window.innerWidth / 2 - 40
                    const dy = window.innerHeight / 2 - 40
                    x = ((x + Math.sign(x) * dx) % window.innerWidth) - Math.sign(x) * dx
                    y = ((y + Math.sign(y) * dy) % window.innerHeight) - Math.sign(y) * dy
                }
                // apiOuter.start({
                //     x: active || gesture === 'offset' ? x : 0,
                //     y: active || gesture === 'offset' ? y : 0,
                //     immediate: pointerOptions.lock
                // })
            }
        },
        config3
    )

    const config4= {
        // filterTaps: false,
        // triggerAllEvents: false,
        // pointer: { touch: false, },
    } as UserDragConfig;

    // @ts-ignore
    // @ts-ignore
    const bind = useDrag(
        (state) => {
            const { event, active, intentional, tap, canceled, direction: [xDir,yDir], movement: [mx,my], cancel, ...other }=state;
            console.log("Pagerer四层 graphql入口data=" ,state);
            event.stopPropagation()
            if (intentional) {
                if(xDir > 0 &&  mx> 50  && Math.abs(mx)>Math.abs(my)){
                    console.log("Pagerer四层 触发！！" ,state);
                    cancel();
                    return;
                }
                // @ts-ignore
                let [x, y] = other[gesture];
                set({ x, y })

                if (pointerOptions.lock) {
                    const dx = window.innerWidth / 2 - 40
                    const dy = window.innerHeight / 2 - 40
                    x = ((x + Math.sign(x) * dx) % window.innerWidth) - Math.sign(x) * dx
                    y = ((y + Math.sign(y) * dy) % window.innerHeight) - Math.sign(y) * dy
                }
                api.start({
                    x: active || gesture === 'offset' ? x : 0,
                    //y: active || gesture === 'offset' ? y : 0,
                    immediate: pointerOptions.lock
                })
            }
        },
        config4
    )

    const theme = useTheme();
    const [filter, setFilter] = React.useState<any>( {} );

    const [form, setForm] = React.useState({ username: "", password: "",
          mobile:''} as any);
    async function doLogin(e: React.FormEvent  | Event)
    {
        console.log("点了form",form);
    }

    return <animated.div  {...({ } as any)}
                 ref={ref3}
                    {...bindOuter()} className="styles.hover" style={styleOuter}
                  css={{
                      cursor: 'grab',
                      touchAction: 'none',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      height: '310px',
                      width: '310px',
                      backgroundColor: 'royalblue',
                      ":hover": {
                          backgroundColor: 'darkblue',
                      }
                  }}
    >
        <animated.div   {...({ } as any)}
                      tabIndex={-1} {...bind()  } className="styles.drag" style={style}
                      css={{
                          height: '220px',
                          width: '220px',
                          backgroundColor: 'rgb(255 255 255 / 70%)',
                          cursor: 'grab',
                          touchAction: 'none',
                          // userSelect: 'none',
                          fontSize: '10px',
                      }}
        >
            <div  style={{ backgroundColor: color }}
                 css={{
                     width: '100%',
                     height: '100%',
                     backgroundColor: '#000',
                     color: '#fff',
                     display: 'flex',
                     flexDirection: 'column',
                     alignItems: 'center',
                     // justifyContent: 'center',
                     fontFamily: 'monospace',
                 }}
            >
                <TabPanel id="company4"
                          css={{
                              height: '100%',
                          }}
                >
                    <form  method="post"
                           onSubmit={e =>{ doLogin(e) } }>
                        <div   css={{  marginTop: theme.spaces.md   }}>
                            <InputGroup  label={"账户"}>
                                <Input  required  type="search"
                                        onChange={e => {
                                            setForm({ ...form, username: e.currentTarget.value });
                                        }}
                                        value={form.username}
                                        inputSize="md"
                                        placeholder="账户"
                                />
                            </InputGroup>
                            <div css={{ display: "flex", justifyContent: "flex-end" }}>
                                <Button
                                    block
                                    component="button"
                                    css={{
                                        textAlign: "center",
                                        width: "100%",
                                        marginTop: theme.spaces.md
                                    }}
                                    type="submit"
                                    size="md"
                                    intent="primary"
                                >
                                    登录1submit
                                </Button>
                                <Button
                                    block
                                    component="button"
                                    css={{
                                        textAlign: "center",
                                        width: "100%",
                                        marginTop: theme.spaces.md
                                    }}
                                    size="md"
                                    intent="primary"
                                    onPress={e =>{ console.log("点onPress",form);
                                        // @ts-ignore
                                        doLogin(e) } }
                                >
                                    登录2onPress
                                </Button>
                            </div>
                        </div>
                    </form>
                </TabPanel>
            </div>
        </animated.div>
    </animated.div>

} );


function Draggable() {
  const ref = React.useRef<HTMLDivElement | null>(null);
    const refPager = React.useRef<HTMLDivElement | null>(null);

  const [color, setColor] = React.useState('white')
  const toggleColor = () => setColor((c) => (c === 'white' ? '#ec625c' : 'white'))

  const [style, api] = useSpring(() => ({ scale: 1, x: 0, y: 0 }))
  const [styleOuter, apiOuter] = useSpring(() => ({scale: 1, x: 0, y: 0 }))
  const [coords, set] = React.useState({ x: 0, y: 0 })

  const { boundToParent, gesture, ...options } = useControls({
    enabled: true,
    gesture: { options: ['offset', 'movement'] },
    axis: { options: [undefined, 'x', 'y', 'lock'] },
    filterTaps: false,
    boundToParent: false,
    rubberband: false,
    triggerAllEvents: true
  })

  const pointerOptions = useControls('pointer', { touch: false, capture: true, lock: false })

    const config1= {
        filterTaps: true,
        triggerAllEvents: true,
        pointer: { touch: false, capture: true, lock: false },
    } as UserDragConfig;

  // const bindOuterOLD = useDrag((state) =>{
  //     const { offset: [x, y] }=state;
  //       console.log("框架层 graphql入口data=" ,state);
  //       apiOuter.start({ x, y })
  //    }
  // )
    const bindOuter = useDrag(
        (state) => {
            const { event, active, intentional, tap, canceled, ...other }=state;
            console.log("框架层 graphql入口data=" ,state);
            event.stopPropagation()
            if (intentional) {
                // @ts-ignore
                let [x, y] = other[gesture];
                set({ x, y })

                if (pointerOptions.lock) {
                    const dx = window.innerWidth / 2 - 40
                    const dy = window.innerHeight / 2 - 40
                    x = ((x + Math.sign(x) * dx) % window.innerWidth) - Math.sign(x) * dx
                    y = ((y + Math.sign(y) * dy) % window.innerHeight) - Math.sign(y) * dy
                }
                apiOuter.start({
                    scale: active ? 1.2 : 1,
                    x: active || gesture === 'offset' ? x : 0,
                    y: active || gesture === 'offset' ? y : 0,
                    immediate: pointerOptions.lock
                })
            }
        },
        config1
    )

  const config2= {
      filterTaps: true,
      triggerAllEvents: true,
      pointer: { touch: false, capture: true, lock: false },
    } as UserDragConfig;


  // @ts-ignore
  // @ts-ignore
  const bind = useDrag(
    (state) => {
      const { event, active, intentional, tap, canceled, ...other }=state;
      console.log("Pagerer二层 graphql入口data=" ,state);
      event.stopPropagation()
      if (intentional) {
        // @ts-ignore
        let [x, y] = other[gesture];
        set({ x, y })

        if (pointerOptions.lock) {
          const dx = window.innerWidth / 2 - 40
          const dy = window.innerHeight / 2 - 40
          x = ((x + Math.sign(x) * dx) % window.innerWidth) - Math.sign(x) * dx
          y = ((y + Math.sign(y) * dy) % window.innerHeight) - Math.sign(y) * dy
        }
        api.start({
          scale: active ? 1.2 : 1,
          x: active || gesture === 'offset' ? x : 0,
          y: active || gesture === 'offset' ? y : 0,
          immediate: pointerOptions.lock
        })
      }
    },
      config2
  )

  return (
    <animated.div  {...({ } as any)}   ref={ref}
                  {...bindOuter()} className="styles.hover"
                  style={styleOuter}
           css={{
             cursor: 'grab',
             touchAction: 'none',
             display: 'flex',
             alignItems: 'center',
             justifyContent: 'center',
             height: '520px',
             width: '520px',
             backgroundColor: 'royalblue',
             ":hover": {
                 backgroundColor: 'darkblue',
             }
           }}
    >
      <animated.div  {...({ } as any)}  ref={refPager}
          tabIndex={-1} {...bind()  } className="styles.drag" style={style}
             css={{
               height: '390px',
               width: '390px',
               backgroundColor: 'rgb(255 255 255 / 70%)',
               cursor: 'grab',
               touchAction: 'none',
                userSelect: 'none',
               fontSize: '10px',
             }}
      >
        <div onClick={toggleColor} style={{ backgroundColor: color }}
             css={{
                 width: '100%',
                 height: '100%',
                 backgroundColor: '#000',
                 color: '#fff',
                 display: 'flex',
                 flexDirection: 'column',
                 alignItems: 'center',
                 // justifyContent: 'center',
                 fontFamily: 'monospace',
             }}
        >
          <span>二层</span>

          <NestedStack ref={refPager} />
        </div>
      </animated.div>
    </animated.div>
  )
}

export default function DragTest() {
  const { shown } = useControls({ shown: true })
    const ref = React.useRef<HTMLDivElement | null>(null);
    const [color, setColor] = React.useState('black')
    const toggleColor = () => setColor((c) => (c === 'black' ? '#ec625c' : 'black'))

    const [style, api] = useSpring(() => ({ scale: 1, x: 0, y: 0 }))
    const [coords, set] = React.useState({ x: 0, y: 0 })

    const { boundToParent, gesture, ...options } = useControls({
        enabled: true,
        gesture: { value: 'movement', options: ['offset', 'movement'] },
        axis: { options: [undefined, 'x', 'y', 'lock'] },
        filterTaps: true,
        boundToParent: false,
        rubberband: false,
        threshold: { value: [3, 3], step: 10 },
        delay: { value: 1000, step: 100, min: 0, max: 3000, optional: true, disabled: true },
        keys: true
    })

    const pointerOptions = useControls('pointer', { touch: false, capture: true, lock: false, mouse: false })
    const config= {
        filterTaps: true,
        triggerAllEvents: true,
        pointer: { touch: false, capture: true, lock: false },
    } as UserDragConfig;
    // @ts-ignore
    const bind = useDrag(
        ({ active, tap, ...state }) => {
            // @ts-ignore
            let [x, y] = state[gesture]
            set({ x, y })

            if (pointerOptions.lock) {
                const dx = window.innerWidth / 2 - 40
                const dy = window.innerHeight / 2 - 40
                x = ((x + Math.sign(x) * dx) % window.innerWidth) - Math.sign(x) * dx
                y = ((y + Math.sign(y) * dy) % window.innerHeight) - Math.sign(y) * dy
            }
            api.start({
                scale: active ? 1.2 : 1,
                x: active || gesture === 'offset' ? x : 0,
                y: active || gesture === 'offset' ? y : 0,
                immediate: pointerOptions.lock
            })
        },
        config
    )

    return (
        <>
            <animated.div  {...({ } as any)}   tabIndex={-1} {...bind()}
                          className=".drag" style={style}
                          css={{
                              cursor: 'grab',
                              touchAction: 'none',
                              backgroundColor: '#ec625c',
                              position: 'absolute',
                              height: '690px',
                              width: '690px',
                          }}
            >
                <div onClick={toggleColor} style={{ backgroundColor: color }}>
                    <span>bind</span>
                    <div className="flex fill center">{shown && <Draggable />}</div>
                </div>
            </animated.div>
            <div ref={ref}  className=".hover"
                 css={{
                     height: '290px',
                     width: '290px',
                     backgroundColor: '#000',
                 }}
            />
        </>
    );
}

